package com.zw.mes.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description: 文件处理工具类
 *
 * @Author: China.sgl
 * @Date: 2020/7/30 9:42
 */
@SuppressWarnings("all")
public class FileUtils {

    /**
     * 判断文件是否存在
     *
     * @param filePath 文件路径
     * @return boolean
     */
    public static boolean isExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * 判断是否为目录
     *
     * @param path 路径
     * @return boolean
     */
    public static boolean isDir(String path) {
        File file = new File(path);
        if (file.exists()) {
            return file.isDirectory();
        } else {
            return false;
        }
    }

    /**
     * 创建目录
     *
     * @param dirPath 路径
     * @return boolean
     */
    public static boolean mkdirs(String dirPath) {
        try {
            File file = new File(dirPath);
            if (!file.exists()) {
                boolean mkdir = file.mkdirs();
                if (!mkdir) {
                    return false;
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 保存文件
     *
     * @param file       文件
     * @param uploadPath 路径
     * @return 上传后的文件名
     */
    public static String upload(MultipartFile file, String uploadPath) {
        if (!file.isEmpty()) {
            String fileName = CommonUtils.urlFormat(file.getOriginalFilename());
            if (!mkdirs(uploadPath)) {
                return null;
            }
            File saveFile = new File(uploadPath + fileName);
            try {
                file.transferTo(saveFile);
            } catch (IOException e) {
                return null;
            }
            return fileName;
        } else {
            return null;
        }
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名
     * @return boolean
     */
    public static boolean delete(String fileName) {
        try {
            File sourceFile = new File(fileName);
            if (sourceFile.isDirectory()) {
                for (File listFile : Objects.requireNonNull(sourceFile.listFiles())) {
                    delete(listFile.getAbsolutePath());
                }
            }
            return sourceFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除文件
     *
     * @param fileName 文件名
     * @return boolean
     */
    public static boolean remove(String fileName) {
        try {
            File sourceFile = new File(fileName);
            return sourceFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 保存图片 BASE64
     *
     * @param dataUrl url
     * @param path    path
     * @param imgName 文件名
     * @throws IOException IOException
     */
    public static void decodeBase64DataUrlToImage(String dataUrl, String path, String imgName) throws IOException {
        String base64 = dataUrl.substring(dataUrl.indexOf(",") + 1);
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileOutputStream write = new FileOutputStream(new File(path + imgName));
        byte[] decoderBytes = Base64.getDecoder().decode(base64);
        write.write(decoderBytes);
        write.close();
    }

    /**
     * 打包文件
     *
     * @param fileNames 文件集合
     */
    public static void zipFileAll(List<String> fileNames, HttpServletResponse response) {
        try {
            File file = new File("e:/download.zip");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            //创建文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            // ZipOutputStream输出流转换
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 接收文件集合、压缩流
            for (String name : fileNames) {
                zipFile(name, zipOutputStream);
            }
            zipOutputStream.close();
            fileOutputStream.close();
            downloadZip(file, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件
     *
     * @param fileName     文件名
     * @param outputStream 输出流
     */
    private static void zipFile(String fileName, ZipOutputStream outputStream) {
        try {
            File file = new File(fileName);
            if (file.exists()) {
                FileInputStream in = new FileInputStream(file);
                BufferedInputStream bins = new BufferedInputStream(in, 1024);
                // 将文件名写入压缩文件中
                ZipEntry entry = new ZipEntry(file.getName());
                outputStream.putNextEntry(entry);
                // 向压缩文件中输出数据
                int nNumber;
                byte[] buffer = new byte[1024];
                while ((nNumber = bins.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, nNumber);
                }
                outputStream.flush();
                bins.close();
                in.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打包下载
     *
     * @param file     文件
     * @param response response
     */
    public static void downloadZip(File file, HttpServletResponse response) {
        downloadFile(file, response);
        try {
            File f = new File(file.getPath());
            f.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名
     * @param response response
     */
    public static void downloadFile(String fileName, HttpServletResponse response) {
        File file = new File(fileName);
        downloadFile(file, response);
    }

    /**
     * 下载文件
     *
     * @param file     文件
     * @param response response
     */
    public static void downloadFile(File file, HttpServletResponse response) {
        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    /**
     * 导入文件
     * @Author: kxx
     * @Date: 2020/10/31 13:04
     * @param file     文件
     * @param cls      实体类型
     * @param listener 解析器
     * @throws IOException IO异常
     */
    public static void importExcel(MultipartFile file, Class cls, AnalysisEventListener listener) throws IOException {
        EasyExcel.read(file.getInputStream(), cls, listener).headRowNumber(1).sheet().doRead();
    }
    /**
     * 生成excel
     * @Author: kxx
     * @Date: 2020/10/31 13:04
     * @param path      路径
     * @param fileName  文件名
     * @param cls       导出模型类
     * @param sheetName sheet名
     * @param list      数据
     */
    public static void genExcel(String path, String fileName, Class cls, String sheetName, List list) {
        mkdirs(path);
        genExcel(path + fileName, cls, sheetName, list);
    }
    /**
     * 生成excel
     * @Author: kxx
     * @Date: 2020/10/31 13:04
     * @param fileName  文件名
     * @param cls       导出模型类
     * @param sheetName sheet名
     * @param list      数据
     */
    public static void genExcel(String fileName, Class cls, String sheetName, List list) {
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, new WriteCellStyle());
        EasyExcel.write(fileName, cls).registerWriteHandler(horizontalCellStyleStrategy).sheet(sheetName).doWrite(list);
    }

}
